﻿import axios from 'axios'
import Qs from 'qs'
import router from '../router'

export default {
  create: function() {
    let token = sessionStorage.getItem('token')
    let ins = axios.create({
      baseURL: 'api/',
      timeout: 100000,
      headers: {
        'Auth': token
      },
      onUploadProgress: function(progressEvent) {
        // 对原生进度事件的处理
      },
      // `onDownloadProgress` 允许为下载处理进度事件
      onDownloadProgress: function(progressEvent) {
        // 对原生进度事件的处理
      },
      paramsSerializer(params) {
        return Qs.stringify(params, {
          arrayFormat: 'brackets',
          allowDots: true
        })
      }
    })
    ins.interceptors.response.use(function(response) {
      return response
    }, function(error) {
      if(error.response) {
        let statusCode = error.response.status
        switch(statusCode) {
          case 401: // 用户未登录，跳转登录页面
            let msgUrl = window.location.href
            router.push({
              path: '/login',
              query: {url: msgUrl} 
            })
            break
          case 403:
            router.push({
              path: '/login'
            })
            break
          case 404:
            router.push({
              path: '/login'
            })
            break
          case 504:
            router.push({
              path: '/login'
            })
            break
          case 500:
          	console.log(error)
            break
          default:
            window.alert('出错了:' + statusCode)
            break
        }
        return Promise.reject(error)
      } else {
        window.alert(error.message)
      }
    })
    return ins
  }
}